<template>
	<view class="card">
		<view class="paycenter">
			<!-- 	<view class="leftIcon">
                <u-icon name="arrow-left" color="#000" size="40"></u-icon>
            </view> -->
			<view class="payText">
				支付中心
			</view>
		</view>
		<view class="price">
			￥{{receivedPayMoney}}
		</view>
		<view @click="goPay" class="wx" v-for="(payment, index) in paymentOptions" :key="index"
			:data-payment="payment.value">
			<view class="wxIcon">
				<image :src="payment.icon" mode="widthFix"></image>
			</view>
			<view class="">
				<view class="">
					{{ payment.name }}<span style="color:#999;font-size:24rpx;margin-left:10rpx">{{payment.name=='微信支付'?'(推荐使用)':'(不推荐)'}}</span>
				</view>
				<view class="gray">
					{{ payment.desc }}
				</view>
			</view>
			<!-- <uni-data-checkbox v-model="radio1" :localdata="sex"></uni-data-checkbox> -->

		</view>
		<!-- 	<view class="confirm">
			确认付款
		</view> -->
	</view>
</template>

<script>
	const app = getApp();
	var util = require('../../utils/util.js');
	export default {
		data() {
			return {
				paymentOptions: [{
						name: "微信支付",
						desc: "使用微信快捷支付",
						icon: "../../static/wxpay.png",
						value: "wechat",
						checked: false,

					},
					{
						name: "支付宝支付",
						desc: "使用支付宝支付",
						icon: "../../static/zfbpay.png",
						value: "alipay",
						checked: false,

					}
				],
				receivedGoodsId: '',
				receivedNumber: 0,
				receivedOrderTime: '',
				receivedUserName: '',
				receivedInfo: '',
				receivedMobile: '',
				receivedMoney: 0,
				receivedPayMoney: 0,
				receivedUserCouponId: '',
				orderId: '',
				orderNumber: '',
				type:0,
				codes:''
			};
		},
		onLoad(options) {
			this.codes = this.getUrlCode().code; 
			console.log(options)
			if(this.codes){
				this.get_openid()
				this.type = uni.getStorageSync('types')
				this.orderId = uni.getStorageSync('orderId')
				this.orderNumber = uni.getStorageSync('orderNumber')
				// 获取各个传递过来的参数并赋值给对应的变量
				this.receivedPayMoney = uni.getStorageSync('receivedPayMoney')
			}else{
				
			// 	console.log(1111)
				this.type = options.type?options.type:0
				this.orderId = options.orderId?options.orderId:'undefined'
				this.orderNumber = options.orderNumber?options.orderNumber:'undefined'
				// 获取各个传递过来的参数并赋值给对应的变量
				this.receivedPayMoney = options.price?options.price:'undefined';
				uni.setStorageSync('types', this.type);
				uni.setStorageSync('orderId', this.orderId);
				uni.setStorageSync('orderNumber', this.orderNumber);
				uni.setStorageSync('receivedPayMoney', this.receivedPayMoney);
				console.log(uni.getStorageSync('orderNumber'))
			}
			// console.log(options, 'oooo');
		},
		methods: {
			get_openid(){
				app.globalData.api.request(`weichat/get_openid?code=${this.codes}`, 'GET').then((res) => {
					if (res && res.openid) {
						uni.setStorageSync('openIds', res.openid);
					} else {
						console.log('跳转失败');
					}
				});
			},
			// 支付
			goPay(e) {
				let that = this
				// 支付宝支付
				if (e.currentTarget.dataset.payment == 'alipay') {
					console.log(123);
					if (uni.getStorageSync('orderNumber') != 'undefined'&&uni.getStorageSync('orderNumber') != undefined) {
						// 从确认订单页面
						if(util.isWechat()==true){
							uni.navigateTo({
								url:'/subcontract/yd?order_number='+uni.getStorageSync('orderNumber')+"&type=1"+"&payment="+e.currentTarget.dataset.payment
							})
						}else{
							app.globalData.api.request('User/orderAliByOrderNumber', {
								order_number: uni.getStorageSync('orderNumber')
							}, 'POST', 'form').then((res) => {
								console.log(res, '11233232');
								if (res.code == 0) {
									// console.log(res, '11233232');
									uni.setStorageSync('paytype', 1)
									window.open(res.data, '_self');
								} else {
									if (res.msg == '亲登陆') {
										wx.navigateTo({
											url: "/pages/login/index"
										})
									}
								}
							})
						}
						
					} else {
						// 从待付款页面
						if(util.isWechat()==true){
							uni.navigateTo({
								url:'/subcontract/yd?order_number='+uni.getStorageSync('orderId')+"&type=2"+"&payment="+e.currentTarget.dataset.payment
							})
						}else{
							app.globalData.api.request('User/orderAliByOrderId', {
								id: uni.getStorageSync('orderId')
							}, 'POST').then((res) => {
								console.log(res, '00303');
								if (res.code == 0) {
									// console.log(res, '11233232');
									uni.setStorageSync('paytype', 1)
									window.open(res.data, '_self');
								} else {
									if (res.msg == '请登陆') {
										wx.navigateTo({
											url: "/pages/login/index"
										})
									}
								}
							})
						}
					}
				} else if (e.currentTarget.dataset.payment == 'wechat') {
					// 从确认订单页
					// if (uni.getStorageSync('orderNumber') != 'undefined'&&uni.getStorageSync('orderNumber') != undefined) {
					// 	if(util.isWechat()==true){
					// 		uni.navigateTo({
					// 			url:'/subcontract/yd?order_number='+uni.getStorageSync('orderNumber')+"&type=1"+"&payment="+e.currentTarget.dataset.payment
					// 		})
					// 	}else{
					// 		app.globalData.api.request(`User/orderPayByOrderNumber`,
					// 			{order_number:uni.getStorageSync('orderNumber')},
					// 			'POST', 'form').then((res) => {
					// 			console.log(res, 'wxwx');
					// 			if (res.code == 0) {
					// 				uni.setStorageSync('paytype', 1)
					// 				 // 仅在H5环境中设置
					// 				 const referer = 'https://saas.mmchengren.com';
					// 				 const url = res.data.h5_url;
					// 				 // 创建一个新的URL对象
					// 				 const urlObj = new URL(url);
					// 				 // 使用自定义的URLSearchParams来设置headers
					// 				 const params = new URLSearchParams(urlObj.search);
					// 				 params.set('redirect_url', referer);
					// 				 // 使用新的URL对象来构建带有headers的URL
					// 				 urlObj.search = params.toString();
					// 				 console.log(urlObj.toString())
					// 				 // 导航到支付链接
					// 				 // window.location.href = urlObj.toString();
					// 				// 拉起支付
					// 			} else {
					// 				if (res.msg == '亲登陆') {
					// 					wx.navigateTo({
					// 						url: "/pages/login/index"
					// 					})
					// 				}
					// 			}
					// 		})
						
					// 	}
					// } else {
					// 	if(util.isWechat()==true){
					// 		uni.navigateTo({
					// 			url:'/subcontract/yd?order_number='+uni.getStorageSync('orderNumber')+"&type=2"+"&payment="+e.currentTarget.dataset.payment
					// 		})
					// 	}else{
					// 		app.globalData.api.request(`User/orderPayByOrderId`,
					// 			{id:uni.getStorageSync('orderId')},
					// 			'POST', 'form').then((res) => {
					// 			console.log(res, '微信待付款');
					// 			if (res.code == 0) {
					// 				console.log(res, '11233232');
					// 				uni.setStorageSync('paytype', 1)
					// 				// 仅在H5环境中设置
					// 				const referer = 'https://saas.mmchengren.com';
					// 				const url = res.data.h5_url;
					// 				// 创建一个新的URL对象
					// 				const urlObj = new URL(url);
					// 				// 使用自定义的URLSearchParams来设置headers
					// 				const params = new URLSearchParams(urlObj.search);
					// 				params.set('redirect_url', referer);
					// 				// 使用新的URL对象来构建带有headers的URL
					// 				urlObj.search = params.toString();
					// 				console.log(urlObj.toString())
					// 				// 导航到支付链接
					// 				window.location.href = urlObj.toString();
					// 				// 拉起支付
					// 			} else {
					// 				if (res.msg == '请登陆') {
					// 					wx.navigateTo({
					// 						url: "/pages/login/index"
					// 					})
					// 				}
					// 			}
					// 		})
					// 	}
					// }
					// 原有jsapi微信支付
					const openId = uni.getStorageSync('openIds')
					var local = encodeURIComponent(window.location.href); // 当前H5页面的url
					this.codes = this.getUrlCode().code; // 截取code
					// 只有在微信网页里并且没有oenid的时候才会有弹窗提醒  如果有openid把openid存在本地在登录的时候把openid作为参数传递给后台
					if (util.isWechat() == true && !openId) {
						if (this.codes == null || this.codes === '' || this.codes == undefined) {
							const authorizeUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf84fdd1d59ea8c39&redirect_uri='+local+'&response_type=code&scope=snsapi_base#wechat_redirect'
								// 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx96abde2c5c085ba7&redirect_uri=https%3A%2F%2Fsaas.mmchengren.com%2F%23%2Fpages%2FexternalPage%2FexternalPage&response_type=code&scope=snsapi_base#wechat_redirect'
							uni.showModal({
								content: '请同意微信授权',
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										window.location.href = authorizeUrl;
									}
								}
							})
							return true
						}
					}
					// 微信支付
					// 从确认订单页
					if (uni.getStorageSync('orderNumber') != 'undefined'&&uni.getStorageSync('orderNumber') != undefined) {
						app.globalData.api.request(`User/orderWeichatpay`,
							{orderNumber:uni.getStorageSync('orderNumber'),openid:openId},
							'POST', 'form').then((res) => {
							console.log(res, 'wxwx');
							if (res.code == 0) {
								console.log(res, '11233232');
								uni.setStorageSync('paytype', 1)
								 // 仅在H5环境中设置
								 // const referer = 'https://saas.mmchengren.com';
								 // const url = res.data.h5_url;
								 									 
								 // // 创建一个新的URL对象
								 // const urlObj = new URL(url);
								 									 
								 // // 使用自定义的URLSearchParams来设置headers
								 // const params = new URLSearchParams(urlObj.search);
								 // params.set('Referer', referer);
								 // // 使用新的URL对象来构建带有headers的URL
								 // urlObj.search = params.toString();
								 
								 // console.log(urlObj.toString())
								 // // 导航到支付链接
								 // window.location.href = urlObj.toString();
								// 拉起支付
								that.wechatPay(res.data.data,res.data.order_id)
							} else {
								if (res.msg == '亲登陆') {
									wx.navigateTo({
										url: "/pages/login/index"
									})
								}
							}
						})
					} else {
						app.globalData.api.request(`user/orderWeichatpayId`,
							{id:uni.getStorageSync('orderId'),openid:openId},
							'POST', 'form').then((res) => {
							console.log(res, '微信待付款');
							if (res.code == 0) {
								console.log(res, '11233232');
								// uni.setStorageSync('paytype', 1)
								// // 仅在H5环境中设置
								// const referer = 'https://saas.mmchengren.com';
								// const url = res.data.h5_url;
																	 
								// // 创建一个新的URL对象
								// const urlObj = new URL(url);
																	 
								// // 使用自定义的URLSearchParams来设置headers
								// const params = new URLSearchParams(urlObj.search);
								// params.set('Referer', referer);
								// // 使用新的URL对象来构建带有headers的URL
								// urlObj.search = params.toString();
								// console.log(urlObj.toString())
								// // 导航到支付链接
								// window.location.href = urlObj.toString();
								// 拉起支付
								that.wechatPay(res.data,that.orderId)
							} else {
								if (res.msg == '请登陆') {
									wx.navigateTo({
										url: "/pages/login/index"
									})
								}
							}
						})
					}
				}
			},

			getUrlCode() {
				// 截取url中的code方法
				var that = this;
				var url = location.href; //获取打开的公众号的路径
				let winUrl = url;
				//console.log(winUrl)
				var theRequest = new Object();
				if (url.indexOf('?') != -1) {
					var str = url.substr(url.indexOf('?') + 1);
					var strs = str.split('&');
					for (var i = 0; i < strs.length; i++) {
						var items = strs[i].split('=');
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
					}
				}
				console.log(theRequest)
				return theRequest;
			},
			wechatPay(data,order_id){
				console.log(data)
				if (typeof WeixinJSBridge == "undefined"){
				   if( document.addEventListener ){
				       document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
				   }else if (document.attachEvent){
				       document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
				       document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
				   }
				}else{
				   WeixinJSBridge.invoke(
					 'getBrandWCPayRequest', data,
					 function(res){
						console.log(res,'支付结果112233')
						if(res.err_msg == "get_brand_wcpay_request:ok" ){
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							wx.navigateTo({
								url: "/subcontract/shop/orderdetails?id="+order_id
							})
						} 
				  });
				}
			}
		}
	};
</script>

<style lang="scss">
	.card {
		width: 100%;
		position: relative;
	}

	.price {
		width: 100%;
		text-align: center;
		font-size: 60rpx;
		margin: 20rpx 25rpx 20rpx 0;
	}

	.confirm {
		position: absolute;
		bottom: 50rpx;
		left: 120rpx;
		width: 60%;
		height: 100rpx;
		// margin: 0 auto;
		padding: 0px 30rpx;
		// height: 60rpx;
		background: #8665AF;
		border-radius: 5px;
		text-align: center;
		line-height: 100rpx;
		font-family: Source Han Sans, Source Han Sans;
		font-weight: 400;
		font-size: 30rpx;
		color: #fff;
		// margin-left: 12px;
		// float: left;

	}

	.card {

		width: 100%;
		height: 100vh !important;
		background-color: #f0f0f0;
	}

	.paycenter {
		display: flex;
		justify-content: center;
		align-items: end;
		font-size: 45rpx;
		width: 100%;
		height: 265rpx;
		background: url('../../static/bjimg.png');
		// text-align: center;
		// background-size: contain;
		border-radius: 0 0 40rpx 40rpx;
		background-size: 100% auto;

		// padding-top: 220rpx;
		.payText {
			padding-bottom: 20rpx;
			color: #fff;

		}
	}

	.wx {
		width: 80%;
		height: 120rpx;
		margin: 30rpx auto;
		border-radius: 30rpx;
		display: flex;
		background-color: white;
		align-items: center;
		padding: 20rpx;
		box-sizing: border-box;



	}

	.wxIcon {
		width: 10%;
		height: 70%;
		margin-right: 30rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.leftIcon {
		position: relative;
		bottom: 20rpx;
		// left: 30rpx;
	}

	.gray {
		font-size: 22rpx;
		color: gray;
		margin-top: 10rpx;
	}
</style>